package com.yj.springbootmiaosha.controller;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class RedissonLockController {

    /**
     * 使用 java api 实现redisson 分布式锁
     * @return
     */
    @GetMapping("redissonLock")
    public String redissonLock(){
        log.info("进入方法！");
        Config config = new Config();
        // useSingleServer：单个服务
        config.useSingleServer().setAddress("redis://192.168.152.12:6379").setPassword("123456");

        RedissonClient redission = Redisson.create(config);
        RLock rLock = redission.getLock("/order");
        //1、获取锁
        try {
            rLock.lock(10, TimeUnit.SECONDS);
            log.info("获取锁！");
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //2、释放锁
            rLock.unlock();
            log.info("释放锁！");
        }
        log.info("执行结束！");
        return "执行结束！";
    }


    /**
     * 使用springboot 实现分布式锁
     */
    @Resource
    RedissonClient redissonClient;

    @GetMapping("redissonLock2")
    public String redissonLock2(){

        RLock rLock = redissonClient.getLock("/order");
        //1、获取锁
        try {
            rLock.lock(10, TimeUnit.SECONDS);
            log.info("获取锁！");
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //2、释放锁
            rLock.unlock();
            log.info("释放锁！");
        }
        log.info("执行结束！");
        return "执行结束！";
    }

}
